<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\Code\HttpResponse;
use App\Services\TokenService;
use Illuminate\Support\Facades\Log;

class TokenController extends BaseController
{
    /**
     * @var string
     */
    private $appid;
    /**
     * @var string
     */
    private $secret;

    public function __construct()
    {
        $this->appid  = env('MINI_APPID');
        $this->secret = env('MINI_SECRET');
    }

    /**
     * 获取token
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @api {GET} /token 获取token
     * @apiVersion 1.0.0
     * @apiName getToken
     * @apiGroup Token
     * @apiDescription 获取token
     *
     * @apiParam {string} appid  appid
     * @apiParam {string} sign  签名（按照签名规则生成）sha1($secret . md5($appid) . $timestamp);
     * @apiParam {int} timestamp  timestamp（要求和签名时使用的时间戳一致）
     *
     * @apiSuccessExample {json} success:
     *     {"code":200,"message":"success","data":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIiwianRpIjoia3M1dSJ9.eyJpc3MiOiJodHRwOlwvXC9rczV1LmFwaS5pa2FpZmEudG9wIiwiYXVkIjoiaHR0cDpcL1wva3M1dS50ZXN0LmlrYWlmYS50b3AiLCJqdGkiOiJrczV1IiwiaWF0IjoxNTkxMTQwMDY1LCJuYmYiOjE1OTExNDAxMjUsImV4cCI6MTU5MTE0NzI2NSwic2VjcmV0IjoiOGxRUV52aFpFZkw3RSRxNyJ9."}}
     * @apiErrorExample {json} fail:
     *     {"code":1003,"message":"params err"}
     */
    public function getToken()
    {
        Log::info('request params', request()->input());

        $appid     = request()->input('appid', '');
        $sign      = request()->input('sign', '');
        $timestamp = (int)request()->input('timestamp', 0);

        if (!$appid || !$sign || !$timestamp || $appid != $this->appid) {
            Log::error('params err', request()->input());

            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_PARAMS_ERR, 'params err'));
        }

        // md5,sha1验证
        $encryption = TokenService::getSign($this->appid, $this->secret, $timestamp);
        if ($sign !== $encryption) {
            Log::error('secret err', request()->input());

            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_PARAMS_ERR, 'secret err'));
        }

        $permitted = env('MINI_PERMITTED');
        try {
            $token = TokenService::getToken($permitted, $this->appid, $this->secret);

            return response()->json(HttpResponse::respSuccess(HttpResponse::CODE_SUCCESS, ['token' => $token]));
        } catch (\Throwable $e) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_TOKEN_GETERR));
        }
    }
}
